import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import dayjs from 'dayjs';
import * as echarts from 'echarts';
import Echarts from '@kuiper-components/echarts';
import { datetime } from '../../../../../common/formatter';
import RadioButton from '../../../../components/RadioButton';
import ChartTitle from '../../../../components/ChartTitle';
import s from './style.module.css';

const numFormat = function (num) {
	try {
		return new Intl.NumberFormat('en-US').format(num);
	} catch {
		return num.toLocaleString('en-US')
	}
}

const CATE_MAP = {
	all: '全部',
	add: '域名上线',
	remove: '域名下线',
};

const emptyLineData = [];
for (let i = 7; i >= 1; i--) {
	emptyLineData.push([
		dayjs().subtract(i, 'days').startOf('day').toDate(),
		0,
		0,
		0,
		0,
		0,
	]);
}

function DomainTrend({ className, tasks, detectTime, dateRask, jobId }) {
	const [status, setStatus] = React.useState('all');
	const [myChart, setChart] = React.useState(undefined);

	const initLineData = React.useMemo(() => {
		const res = tasks.reduce((arr, t) => {
			const warnings = t?.result?.warnings || [];
			const info = warnings.reduce(
				(obj, w) => {
					const type = w?.detail?.op;
					if (type) {
						obj[`${type}Count`]++;
					}
					return obj;
				},
				{
					datetime: new Date(t?.endTime),
					allCount: warnings?.length || 0,
					removeCount: 0,
					addCount: 0,
				}
			);

			arr.push(info);
			return arr;
		}, []);
		return res;
	}, [tasks]);

	const lineOption = {
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross',
			},
			formatter([{ data, seriesName }]) {
				if (seriesName === '全部') {
					return `<div>
										<div style="border-bottom: 1px solid var(--color-border-2);padding: 0.5rem 1.25rem;">
											${datetime(data[0])}
										</div>
										<div>
										<div style="display: flex; padding: 0.5rem 1.25rem;">
												<div>域名变动</div>
												<div style="width: 5rem;text-align: right;">${numFormat(data[1])}个</div>
											</div>
										<div style="display: flex; padding: 0.5rem 1.25rem;">
												<div>域名上线</div>
												<div style="width: 5rem;text-align: right;">${numFormat(data[2])}个</div>
											</div>
											<div style="display: flex; padding: 0.5rem 1.25rem;">
												<div>域名下线</div>
												<div style="width: 5rem;text-align: right;">${numFormat(data[3])}个
												</div>
											</div>
										 </div>
									</div>`;
				} else {
					return `<div>
					<div style="border-bottom: 1px solid var(--color-border-1);padding: 0.5rem;">
						${datetime(data[0])}
					</div>
					<div>
						<div style="display: flex; padding: 0.5rem 1.25rem;">
							<div>${seriesName}</div>
							<div style="width: 5rem;text-align: right;">${numFormat(data[1])}个</div>
						</div>
					</div>
				</div>`;
				}
			},
			backgroundColor: '#fff',
			textStyle: '#696C78',
			extraCssText:
				'width: 10rem;color: var(--color-text-1);line-height:1rem;margin: 0 auto;',
		},
		grid: {
			left: '60',
			right: '110',
			top: '50',
			bottom: '30',
			containLabel: true
		},
		axisPointer: {
			show: true,
			lineStyle: {
				width: 2,
				type: 'dotted',
				color: '#F0443C',
			},
		},
		xAxis: {
			type: 'time',
			boundaryGap: false,
			splitNumber: 7,
			splitLine: { show: false },
			axisLine: { lineStyle: { color: 'transparent' }, show: false },
			axisTick: {
				show: false,
			},
			axisLabel: {
				formatter(value) {
					const date = new Date(value);
					return datetime(date, 'YYYY-MM-DD HH:mm:ss');
				},
				showMaxLabel: false,
				margin: 20,
				align: 'left',
			},
		},
		yAxis: {
			type: 'value',
			boundaryGap: false,
			axisTick: {
				show: false,
			},
			axisLine: { lineStyle: { color: 'transparent' } },
			splitLine: {
				show: true,
				lineStyle: {
					color: '#F7F9FC',
				},
			},
		},
		textStyle: { color: '#696C78', fontSize: 12 },
		series: [
			{
				data: [],
				name: '全部',
				type: 'line',
				smooth: true,
				smoothMonotone: 'x',
				showSymbol: false,
				lineStyle: {
					color: '#F0443C',
					width: 2,
				},
				areaStyle: {
					color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
						{
							offset: 0,
							color: 'rgba(240, 64, 56, 0.3646)',
						},
						{
							offset: 1,
							color: 'rgba(249, 116, 105, 0.0001)',
						},
					]),
				},
			},
		],
	};

	let highLightIdx = -1;
	if (detectTime) {
		highLightIdx =
			detectTime === 'last' ? initLineData.length - 1 : initLineData.length - 2;
	}

	let lineData = [];
	if (status === 'all') {
		lineData = initLineData.map(item => {
			return [item.datetime, item.allCount, item.addCount, item.removeCount];
		});
	} else if (status === 'add') {
		lineData = initLineData.map(item => {
			return [item.datetime, item.addCount];
		});
	} else {
		lineData = initLineData.map(item => {
			return [item.datetime, item.removeCount];
		});
	}
	if (lineData.length === 0 && jobId) {
		lineData = JSON.parse(JSON.stringify(emptyLineData))
		lineOption.tooltip.show = false
		lineOption.axisPointer.show = false
		lineOption.series[0].lineStyle.width = 0
		lineOption.yAxis.splitNumber = 5
		lineOption.yAxis.max = 5
		lineOption.yAxis.min = 0
	}
	const chartLineData = lineData.reverse();

	if (highLightIdx > -1 && detectTime !== 'range') {
		lineOption.series[0].markPoint = {
			label: {
				formatter: `${detectTime === 'last' ? '最新一次监测' : '上次监测'}`,
				position: 'top',
			},
			data: [{ coord: chartLineData[highLightIdx] }],
			symbolSize: 24,
			itemStyle: {
				color: '#F1443C',
			},
		};
	} else {
		lineOption.series[0].markPoint = {};
	}

	lineOption.series[0].data = chartLineData;
	lineOption.series[0].name = CATE_MAP[status];

	if (chartLineData.length === 0 && dateRask.dateRange) {
		lineOption.series[0].data = [
			[Date.parse(dateRask.dateRange[0]), 0, {}],
			[Date.parse(dateRask.dateRange[1]), 0, {}],
		];
		lineOption.series[0].lineStyle = {
			width: 0,
		};
		lineOption.axisPointer.lineStyle = {
			type: 'dotted',
			width: 0,
		};
	}
	const getChart = e => {
		setChart(e);
	};

	if (myChart) {
		myChart.clear()
		myChart.setOption(lineOption);
	}

	return (
		<div className={cn(className, s.domainTrend)}>
			<div className={s.header}>
				<ChartTitle>域名变动趋势</ChartTitle>
				<div className={s.levelSelect}>
					{Object.entries(CATE_MAP).map(([value, label]) => (
						<RadioButton
							key={value}
							onChecked={() => setStatus(value)}
							checked={status === value}
							className={s.radio}
						>
							{label}
						</RadioButton>
					))}
				</div>
			</div>
			<Echarts className={s.chart} getInstance={getChart} option={lineOption} />
		</div>
	);
}

DomainTrend.propTypes = {
	className: PropTypes.string,
	tasks: PropTypes.arrayOf(
		PropTypes.shape({
			_id: PropTypes.string,
			target: PropTypes.string,
			result: PropTypes.object,
		})
	),
	detectTime: PropTypes.string,
	dateRask: PropTypes.object,
};
DomainTrend.defaultProps = {
	className: '',
};

export default DomainTrend;
